import 'dart:convert';

import 'package:webview_flutter/webview_flutter.dart';

import '../../helper/global/user/logic.dart';
import '../../helper/utils/util.dart';
import 'index.dart';

class WebController extends GetxController {
  WebController();

  final state = WebViewState();

  /// 在 widget 内存中分配后立即调用。
  @override
  void onInit() {
    super.onInit();
    state.url = Get.parameters['url'];
    state.title = Get.parameters['title'];
    state.webCtrl = WebViewController()
      ..setJavaScriptMode(JavaScriptMode.unrestricted)
      ..setNavigationDelegate(NavigationDelegate(
        onPageStarted: (url) {
          Get.log('onPageStarted$url');
        },
        onPageFinished: (url) {
          Get.log('onPageFinished$url');
        },
        onWebResourceError: (error) {
          Get.log(error.description);
        },
        onUrlChange: (change) {
          Get.log("onUrlChange--${change.url ?? ''}");
          if (change.url == null) {
            return;
          }
          var isWebCanBack = !(change.url!.endsWith("#/login") ||
              change.url!.endsWith("#/home"));
          if (state.isWebCanBack != isWebCanBack) {
            state.isWebCanBack = isWebCanBack;
            update();
          }
        },
      ));
    state.webCtrl.addJavaScriptChannel(
      'getUser',
      onMessageReceived: (p0) async {
        var json = jsonEncode(UserController.instance.state.user!.toJson());
        Get.log("resUser--\n$json");
        state.webCtrl.runJavaScript("resUser($json)");
      },
    );

    state.webCtrl.addJavaScriptChannel(
      'logOut',
      onMessageReceived: (p0) async {
        UserController.instance.loginOutSuccess();
        Get.offAllNamed(RouterPath.login);
      },
    );
    if (!isNilStr(state.url)) {
      Uri uri;
      if (state.url!.startsWith('http')) {
        uri = Uri.parse(state.url!);
        state.webCtrl.loadRequest(uri);
      } else {
        state.webCtrl.loadFile(state.url!);
      }
    }
  }

  /// 在 onInit() 之后调用 1 帧。这是进入的理想场所
  @override
  void onReady() {
    super.onReady();
  }

  /// 在 [onDelete] 方法之前调用。
  @override
  void onClose() {
    super.onClose();
  }

  /// dispose 释放内存
  @override
  void dispose() {
    super.dispose();
  }
}
